<script setup lang="tsx">
import { reactive, ref } from 'vue';
import { postAction } from '@/service/request/action';
import { getNoOpenCourseStudentApi } from '@/service/path/train/student';
import { OtherUtils } from '@/utils/other.utils';
import { createOpenCourseInfoApi } from '@/service/path/train/course';
import { StatusMessage } from '@/enum';

interface Emits {
  (e: 'refreshList'): void;
}

const emit = defineEmits<Emits>();

const formRef = ref();
const state = reactive({
  isShowDialog: false,
  loading: false,
  courseId: '',
  dataList: [],
  checkedRowKeys: [],
  columns: [
    {
      type: 'selection',
    },
    {
      title: '序号',
      key: 'index'
    },
    {
      title: '学生姓名',
      key: 'name'
    },
    {
      title: '所属班级',
      key: 'className'
    },
    {
      title: '性别',
      key: 'sex',
      render: (row: Api.Train.Student) => {
        if (row.sex === 1) {
          return '男';
        }
        if (row.sex === 2) {
          return '女';
        }
      }
    }
  ]
});
const openDialog = (id: string) => {
  state.isShowDialog = true;
  state.courseId = id;
  state.checkedRowKeys = [];
  getDataList();
};
const getDataList = () => {
  postAction(getNoOpenCourseStudentApi, {
    id: state.courseId
  }).then(res => {
    if (!res.error) {
      state.dataList = OtherUtils.createDataListIndex(res.data.data);
    }
  });
};
const closeDialog = () => {
  state.isShowDialog = false;
};
const clickConfirm = () => {
  if (!state.checkedRowKeys.length) {
    window.$message?.error('请选择学生');
    return;
  }
  state.loading = true;
  postAction(createOpenCourseInfoApi, {
    studentIds: state.checkedRowKeys,
    courseId: state.courseId
  }).then(res => {
    state.loading = false;
    if (!res.error) {
      window.$message.success(StatusMessage.SUCCESS);
      emit('refreshList');
      closeDialog();
    }
  });
};
defineExpose({
  openDialog
});
</script>

<template>
  <n-modal v-model:show="state.isShowDialog" preset="dialog" title="未开课学生"
           style="width: 60%;" :show-icon="false" :close-on-esc="false" :mask-closable="false">
    <n-data-table
      :columns="state.columns"
      :data="state.dataList"
      :row-key="row => row.id"
      :loading="state.loading"
      v-model:checked-row-keys="state.checkedRowKeys"
      flex-height
      :style="{
        height: `calc(${60 + state.dataList.length * 46}px)`,
        maxHeight: '240px'
      }"
    />
    <template #action>
      <n-space justify="end">
        <n-button @click="closeDialog">取消</n-button>
        <n-button type="primary" @click="clickConfirm" :loading="state.loading">确定</n-button>
      </n-space>
    </template>
  </n-modal>
</template>

<style scoped>

</style>
